package fr.umlv.search;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.ResourceBundle;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.ListSelectionModel;
import javax.swing.TransferHandler;
import javax.swing.UIManager;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.MouseInputAdapter;
import javax.swing.filechooser.FileSystemView;

import kiyut.ekspos.BrowserWindow;

import org.apache.chemistry.opencmis.client.api.CmisObject;
import org.flexdock.view.View;

import fr.umlv.authentication.SessionHandler;
import fr.umlv.cmis.listview.ViewComponent;
import fr.umlv.model.ClientModel;

// TODO: Auto-generated Javadoc
/**
 * The Class SearchWindowResult.
 */
public class SearchWindowResult extends JPanel{
	
	/** The bundle. */
	ResourceBundle bundle = ResourceBundle.getBundle("kiyut.ekspos.BrowserWindow",SessionHandler.getLocale());
	
	
	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = 1L;

	/** The Constant VS_DETAIL. */
    public static final int VS_DETAIL = 0;
    
    /** The Constant VS_LIST. */
    public static final int VS_LIST = 1;
    
    /** The Constant VS_ICON. */
    public static final int VS_ICON = 2;
    
    /** The Constant VS_THUMBNAIL. */
    public static final int VS_THUMBNAIL = 3;
    
    /** The search model. */
    protected SearchModel searchModel;
    
    /** The search selection model. */
    protected SearchSelectionModel searchSelectionModel;
    
    /** The scroll pane. */
    protected JScrollPane scrollPane;
    
    /** The detail view search. */
    protected DetailViewSearch detailViewSearch;
    
    /** The view style. */
    //protected ListView listView;
    
    /** the icon view of <code>ShellListView</code> */
    //protected CmisIconView iconView;
    
    /** the thumbnail view of <code>ShellListView</code> */
    //protected CmisThumbnailView thumbnailView;
    
    /** the view style of <code>ShellListView</code> */
    protected int viewStyle;
    
	/** The search criters panel. */
	private JPanel searchCritersPanel;
    
    /** The parent. */
    private BrowserWindow parent;
    
    /**
     * Instantiates a new search window result.
     *
     * @param searchModel the search model
     * @param searchCritersPanel the search criters panel
     * @param parent the parent
     */
    public SearchWindowResult(SearchModel searchModel,JPanel searchCritersPanel, BrowserWindow parent) {
        this(FileSystemView.getFileSystemView().getHomeDirectory(),FileSystemView.getFileSystemView(),true,VS_DETAIL,true,searchModel, searchCritersPanel, parent);
        
    }
    
    /**
     * Instantiates a new search window result.
     *
     * @param dir the dir
     * @param fsv the fsv
     * @param useFileHiding the use file hiding
     * @param viewStyle the view style
     * @param thumbnailEnabled the thumbnail enabled
     * @param search the search
     * @param searchCritersPanel the search criters panel
     * @param parent the parent
     */
    public SearchWindowResult(File dir, FileSystemView fsv, boolean useFileHiding, int viewStyle, boolean thumbnailEnabled, SearchModel search, final JPanel searchCritersPanel, BrowserWindow parent) {
        ViewMouseHandler viewMouseHandler = new ViewMouseHandler();
        ViewKeyHandler viewKeyHandler = new ViewKeyHandler();
        
        this.searchModel = search;
        this.parent=parent;
        this.searchCritersPanel=searchCritersPanel;
        searchSelectionModel = new SearchSelectionModel(searchModel);
        
        detailViewSearch = new DetailViewSearch(searchModel);
        detailViewSearch.setSelectionModel(searchSelectionModel);
        detailViewSearch.addMouseListener(viewMouseHandler);
        detailViewSearch.addKeyListener(viewKeyHandler);
        
        /*listView = new ListView(searchModel);
        listView.setSelectionModel(searchSelectionModel);
        listView.addMouseListener(viewMouseHandler);
        listView.addKeyListener(viewKeyHandler);
        
        iconView = new CmisIconView(searchModel);
        iconView.setSelectionModel(searchSelectionModel);
        iconView.addMouseListener(viewMouseHandler);
        iconView.addKeyListener(viewKeyHandler);
        
        thumbnailView = new CmisThumbnailView(searchModel);
        thumbnailView.setSelectionModel(searchSelectionModel);
        thumbnailView.setEnabled(thumbnailEnabled);
        thumbnailView.addMouseListener(viewMouseHandler);
        thumbnailView.addKeyListener(viewKeyHandler);*/
        
        searchModel.addListDataListener(new javax.swing.event.ListDataListener() {
            public void contentsChanged(ListDataEvent evt) { onContentsChanged(evt); }
            public void intervalAdded(ListDataEvent evt) { /* do nothing */ }
            public void intervalRemoved(ListDataEvent evt) { /* do nothing */ }
        });
        
        scrollPane = new JScrollPane();
        
        
        setFileHidingEnabled(useFileHiding);
        setViewStyle(viewStyle);
        
        setBackground(UIManager.getColor("List.background"));
        setForeground(UIManager.getColor("List.foreground"));
        setFont(UIManager.getFont("Table.font"));
        scrollPane.getViewport().setBackground(getBackground());
        
        
        setLayout(new BorderLayout());
        add(scrollPane,BorderLayout.CENTER);
             
        this.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent evt) { SearchResultClicked(evt); }
		});
        
        JButton buttonback = new JButton(bundle.getString("search_new_search"));
        JButton buttonback2 = new JButton(bundle.getString("search_new_search"));
        
        final SearchWindowResult searchWindowResult = this;
        
        
        buttonback.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				searchWindowResult.reinitializeSearch();		
			}
		});
        
        buttonback2.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				searchWindowResult.reinitializeSearch();		
			}
		});
        
        
        this.add(buttonback, BorderLayout.NORTH);
        this.add(buttonback2, BorderLayout.SOUTH);
        
        //refresh();
        
        //updateUI();
    }
    
    /**
     * Instantiates a new search window result.
     */
    public SearchWindowResult(){
    	this.add(new JLabel("SEARCHWINDOWRESULT"));
    	this.setVisible(true);
    }
    
    /**
     * Search result clicked.
     *
     * @param evt the evt
     */
    public void SearchResultClicked(MouseEvent evt) {
		if (evt.getClickCount() == 2) {
			openActionPerformed();
		}
	}
    
    /**
     * Open action performed.
     */
    private void openActionPerformed() {

		// Get the name of selected files
		List<CmisObject> selectedList = this.getSelectedFiles();
		if (selectedList != null) {
			for (CmisObject file : selectedList) {
				try {
					ClientModel.openCmisObject(file);
				} catch (IOException e) {
					JOptionPane.showMessageDialog(this,
							bundle.getString("OpenImpossible.text"), "Error",
							JOptionPane.ERROR_MESSAGE);
				}

			}
		}

	}
    
    /**
     * Gets the model.
     *
     * @return the model
     */
    /*public void paintComponent(Graphics g) {
        super.paintComponent(g);
        //scrollPane.getViewport().setBackground(getBackground());
    }*/
    
    
    
    /** Returns the <code>ShellListViewModel</code> that provides the data displayed by this component.
     * @return the <code>ShellListViewModel</code> that provides the data displayed by this component.
     */
    public SearchModel getModel() {
        return searchModel;
    }
    
    /**
     * Gets the last selected index.
     *
     * @return the last selected index
     */
    public int getLastSelectedIndex() {
        return searchSelectionModel.getLastSelectedIndex();
    }
    
    /**
     * Gets the last selected file.
     *
     * @return the last selected file
     */
    public CmisObject getLastSelectedFile() {
        return searchSelectionModel.getLastSelectedFile();
    }
    
    /**
     * Gets the selected files.
     *
     * @return the selected files
     */
    public List<CmisObject> getSelectedFiles() {
        return searchSelectionModel.getSelectedFiles();
    }
    
    /**
     * Gets the all files.
     *
     * @return the all files
     */
    public List<CmisObject> getAllFiles() {
        return searchSelectionModel.getAllFiles();
    }
    
    /**
     * Refresh.
     */
    public void refresh() {
        searchModel.refresh();
    }
    
    /**
     * Gets the view style.
     *
     * @return the view style
     */
    public int getViewStyle() {
        return this.viewStyle;
    }
    
    /**
     * Sets the view style.
     *
     * @param viewStyle the new view style
     */
    public void setViewStyle(int viewStyle) {
        if (viewStyle == VS_DETAIL) {
            scrollPane.setViewportView(detailViewSearch);
            this.viewStyle = viewStyle;
        /*} else if (viewStyle == VS_LIST) {
            scrollPane.setViewportView(listView);
            this.viewStyle = viewStyle;
        } else if (viewStyle == VS_ICON) {
            scrollPane.setViewportView(iconView);
            this.viewStyle = viewStyle;
        } else if (viewStyle == VS_THUMBNAIL) {
            scrollPane.setViewportView(thumbnailView);
            this.viewStyle = viewStyle;*/
        } else {
            throw new IllegalArgumentException("Illegal viewStyle");
        }
        
        revalidate();
    }
    
    /**
     * Sets the current directory.
     *
     * @param dir the new current directory
     */
    public void setCurrentDirectory(CmisObject dir) {
        searchModel.setCurrentDirectory(dir);
    }
    
    /**
     * Gets the current directory.
     *
     * @return the current directory
     */
    public CmisObject getCurrentDirectory() {
        return searchModel.getCurrentDirectory();
    }
    
    /**
     * Sets the file hiding enabled.
     *
     * @param useFileHiding the new file hiding enabled
     */
    public void setFileHidingEnabled(boolean useFileHiding) {
        searchModel.setFileHidingEnabled(useFileHiding);
    }
    
    /**
     * Checks if is file hiding enabled.
     *
     * @return true, if is file hiding enabled
     */
    public boolean isFileHidingEnabled() {
        return searchModel.isFileHidingEnabled();
    }
    
    /**
     * Gets the view component.
     *
     * @return the view component
     */
    public ViewComponent getViewComponent() {
        Component comp = scrollPane.getViewport().getView();
        if (comp == null) { return null; }
        return (ViewComponent)comp;
    }
    
    /**
     * Gets the detail view.
     *
     * @return the detail view
     */
    public DetailViewSearch getDetailView() {
        return detailViewSearch;
    }
    
    /**
     * Traves.
     */
    /*public ListView getListView() {
        return listView;
    }*/
    
    /** Return the icon view of this component
     * @return icon view
     */
    /*public CmisIconView getIconView() {
        return iconView;
    }*/
    
    /** Return the ThumbnailView view of this component
     * @return thumbnail view
     */
    /*public CmisThumbnailView getThumbnailView() {
        return thumbnailView;
    }*/
    
    /** Traves the data model based on selectionModel.getMaxSelectionIndex()
     */
    protected void traves() {
        int index = searchSelectionModel.getMaxSelectionIndex();
        if ( (index>=0) && (searchModel.isTraversable(index)) ) {
            CmisObject file = searchModel.getFile(index);
            searchSelectionModel.setValueIsAdjusting(true);
            searchModel.setCurrentDirectory(file);
            searchSelectionModel.setValueIsAdjusting(false);
            searchModel.refresh();
        }
    }
    
    /* (non-Javadoc)
     * @see javax.swing.JComponent#setTransferHandler(javax.swing.TransferHandler)
     */
    @Override
    public void setTransferHandler(TransferHandler newHandler) {
        detailViewSearch.setTransferHandler(newHandler);
        //listView.setTransferHandler(newHandler);
        //iconView.setTransferHandler(newHandler);
        //thumbnailView.setTransferHandler(newHandler);
    }
    
    /**
     * Sets the drag enabled.
     *
     * @param b the new drag enabled
     */
    public void setDragEnabled(boolean b) {
        detailViewSearch.setDragEnabled(b);
        //listView.setDragEnabled(b);
        //iconView.setDragEnabled(b);
        //thumbnailView.setDragEnabled(b);
    }
    
    /**
     * Removes the list selection listener.
     *
     * @param l the l
     */
    public void removeListSelectionListener(ListSelectionListener l) {
        searchSelectionModel.removeListSelectionListener(l);
    }
    
    /**
     * Adds the list selection listener.
     *
     * @param l the l
     */
    public void addListSelectionListener(ListSelectionListener l) {
        searchSelectionModel.addListSelectionListener(l);
    }
    
    /**
     * Adds the list data listener.
     *
     * @param l the l
     */
    public void addListDataListener(ListDataListener l) {
        searchModel.addListDataListener(l);
    }
    
    /**
     * Removes the list data listener.
     *
     * @param l the l
     */
    public void removeListDataListener(ListDataListener l) {
        searchModel.removeListDataListener(l);
    }
    
    /**
     * Adds the cell editor listener.
     *
     * @param l the l
     */
    public void addCellEditorListener(CellEditorListener l) {
        detailViewSearch.getColumnModel().getColumn(0).getCellEditor().addCellEditorListener(l);
        //listView.getCellEditor().addCellEditorListener(l);
        //iconView.getCellEditor().addCellEditorListener(l);
        //thumbnailView.getCellEditor().addCellEditorListener(l);
    }
    
    /**
     * Removes the cell editor listener.
     *
     * @param l the l
     */
    public void removeCellEditorListener(CellEditorListener l) {
        detailViewSearch.getColumnModel().getColumn(0).getCellEditor().removeCellEditorListener(l);
        //listView.getCellEditor().removeCellEditorListener(l);
        //iconView.getCellEditor().removeCellEditorListener(l);
        //thumbnailView.getCellEditor().removeCellEditorListener(l);
    }
    
    /**
     * Edits the cell at.
     *
     * @param index the index
     * @return true, if successful
     */
    public boolean editCellAt(int index) {
        boolean result = false;
        
        searchModel.setState(SearchModel.EDIT);
        switch (viewStyle) {
            case VS_DETAIL:
                result = detailViewSearch.editCellAt(index,0);
                break;
            /*case VS_LIST:
                result = listView.editCellAt(index);
                break;
            case VS_ICON:
                result = iconView.editCellAt(index);
                break;
            case VS_THUMBNAIL:
                result = thumbnailView.editCellAt(index);
                break;*/
            default:
                result = false;
                break;
        }
        
        return result;
    }
    
    /* (non-Javadoc)
     * @see java.awt.Component#addMouseListener(java.awt.event.MouseListener)
     */
    public void addMouseListener(MouseListener l) {
        detailViewSearch.addMouseListener(l);
        //listView.addMouseListener(l);
        //iconView.addMouseListener(l);
        //thumbnailView.addMouseListener(l);
    }
    
    /* (non-Javadoc)
     * @see java.awt.Component#removeMouseListener(java.awt.event.MouseListener)
     */
    public void removeMouseListener(MouseListener l) {
        detailViewSearch.removeMouseListener(l);
        //listView.removeMouseListener(l);
        //iconView.removeMouseListener(l);
        //thumbnailView.removeMouseListener(l);
    }
    
    /* (non-Javadoc)
     * @see java.awt.Component#addKeyListener(java.awt.event.KeyListener)
     */
    public void addKeyListener(KeyListener l) {
        detailViewSearch.addKeyListener(l);
        //listView.addKeyListener(l);
        //iconView.addKeyListener(l);
        //thumbnailView.addKeyListener(l);
    }
    
    /* (non-Javadoc)
     * @see java.awt.Component#removeKeyListener(java.awt.event.KeyListener)
     */
    public void removeKeyListener(KeyListener l) {
        detailViewSearch.removeKeyListener(l);
        //listView.removeKeyListener(l);
        //iconView.removeKeyListener(l);
        //thumbnailView.removeKeyListener(l);
    }
    
    ////////////////////////////////////////////
    // EVENT HANDLER
    ///////////////////////////////////////////
    
    /**
     * On contents changed.
     *
     * @param e the e
     */
    private void onContentsChanged(ListDataEvent e) {
        // changeAll
        if ((e.getIndex0()==SearchModel.ALL_INDEX) &&  (e.getIndex1()==SearchModel.ALL_INDEX) ){
            return;
        }
        
        if (e.getIndex0() != e.getIndex1()) {
            return;
        }
        int index = e.getIndex1();
        if (searchModel.getSize() >= index) {
            searchSelectionModel.setSelectionInterval(index,index);
        }
    }
    
    /**
     * The Class ViewMouseHandler.
     */
    private class ViewMouseHandler extends MouseInputAdapter {
        
        /* (non-Javadoc)
         * @see java.awt.event.MouseAdapter#mouseClicked(java.awt.event.MouseEvent)
         */
        @Override
        public void mouseClicked(MouseEvent evt) {
            if (evt.getClickCount() == 2) {
            	// Open Folder
            	traves();   	
            }
            Point click = new Point(evt.getX(), evt.getY());
            if(detailViewSearch.columnAtPoint(click) == SearchModel.GOTO_LOCATION){
            	String path = (String) searchModel.getValueAt(detailViewSearch.getSelectedRow(),SearchModel.GOTO_LOCATION);
            	CmisObject obj = SessionHandler.getClientSession().getSession().getObjectByPath(path);
            	parent.getShellListView().setCurrentDirectory(obj);
            	parent.getShellListView().refresh();
            	parent.getShellTreeView().setSelection(obj);
            	parent.getShellTreeView().revalidate();
            	parent.getShellTreeView().repaint();
            	
            	View v = parent.mapViewPlugins.get(BrowserWindow.DOCKING_LIST_VIEW);
            	
            	if(v.getParent() instanceof JTabbedPane){
            		JTabbedPane tabbedPane = (JTabbedPane)v.getParent();
            		tabbedPane.setSelectedIndex(0);
            	}
            }   
        } 
    }
    
    /**
     * The Class ViewKeyHandler.
     */
    private class ViewKeyHandler extends KeyAdapter {
        
        /* (non-Javadoc)
         * @see java.awt.event.KeyAdapter#keyPressed(java.awt.event.KeyEvent)
         */
        @Override
        public void keyPressed(KeyEvent evt) {
            if (evt.getKeyCode()==KeyEvent.VK_ENTER) {
                traves();
            }
        }
    }

	/**
	 * Gets the view model.
	 *
	 * @return the view model
	 */
	public SearchModel getViewModel() {
		 return getModel();
	}

	/**
	 * Gets the selection model.
	 *
	 * @return the selection model
	 */
	public ListSelectionModel getSelectionModel() {
		return searchSelectionModel;
	}
	
	/**
	 * Reinitialize search.
	 */
	public void reinitializeSearch(){
		searchCritersPanel.setVisible(true);
		//this.getParent().validate();
		this.setVisible(false);
	}
	

}